import 'package:flutter_base/utils/loading/loading_utils.dart';

import '../../http/http_export.dart';

extension FutureExt on Future {
  Future showLoading() {
    LoadingUtils.showLoading();
    return then((response) {
      LoadingUtils.dismiss();
      return response;
    }, onError: (error) {
      LoadingUtils.dismiss();
      return;
    });
  }

  Future showToast() {
    return then((response) {
      if (response is String && response.isNotEmpty) {
        LoadingUtils.showToast(response);
      } else if (response is HttpResponse && response.isSuccess == false && response.message?.isNotEmpty == true) {
        LoadingUtils.showToast(response.message);
      } else {
        LoadingUtils.dismiss();
      }
      return response;
    }, onError: (error) {
      if (error == null) {
        LoadingUtils.dismiss();
      } else if (error is String) {
        LoadingUtils.showToast(error);
      } else if (error is HttpResponse) {
        LoadingUtils.showToast(error.message);
      } else {
        LoadingUtils.showToast(error.toString());
      }
      return;
    });
  }

  Future showLoadingAndToast() {
    LoadingUtils.showLoading();
    return then((response) {
      if (response is String && response.isNotEmpty) {
        LoadingUtils.showToast(response);
      } else if (response is HttpResponse && response.isSuccess == false && response.message?.isNotEmpty == true) {
        LoadingUtils.showToast(response.message);
      } else {
        LoadingUtils.dismiss();
      }
      return response;
    }, onError: (error) {
      if (error == null) {
        LoadingUtils.dismiss();
      } else if (error is String && error.isNotEmpty) {
        LoadingUtils.showToast(error);
      } else if (error is HttpResponse && error.message?.isNotEmpty == true) {
        LoadingUtils.showToast(error.message);
      } else {
        LoadingUtils.showToast(error.toString());
      }
      return;
    });
  }
}
